package com.renwei.yunlong.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.news.MessageCompanyActivity;
import com.renwei.yunlong.activity.work.GuideListActivity;
import com.renwei.yunlong.adapter.ViewpagerFragmentAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.AppUpdataBean;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.FriendEnterpriseBean;
import com.renwei.yunlong.bean.LoginGuideBean;
import com.renwei.yunlong.event.AppInformationEvent;
import com.renwei.yunlong.event.ChatNotGroupEvent;
import com.renwei.yunlong.event.MainRefreshEvent;
import com.renwei.yunlong.event.MessageRefreshEvent;
import com.renwei.yunlong.event.WorkNumberEvent;
import com.renwei.yunlong.fragment.ChartFragment;
import com.renwei.yunlong.fragment.ContactsFragment;
import com.renwei.yunlong.fragment.MeFragment;
import com.renwei.yunlong.fragment.NewWorkFragment;
import com.renwei.yunlong.fragment.NewsFragment;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.service.LocationService;
import com.renwei.yunlong.utils.AppManager;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PackageUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.view.NoticeMessage;
import com.renwei.yunlong.view.NoticeMessageItemProvider;
import com.renwei.yunlong.view.WebBrowserActivity;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.benjamin.bottombar.NavigationController;
import github.benjamin.bottombar.PageNavigationView;
import github.benjamin.bottombar.item.BaseTabItem;
import github.benjamin.bottombar.tabs.SpecialTab;
import github.benjamin.bottombar.tabs.SpecialTabRound;
import github.opensource.dialog.BeToastUtil;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.MediaMessageContent;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

public class MainActivity extends BaseActivity implements HttpTaskListener {

    private ViewPager viewPager;
    private BaseTabItem tabsMessage;
    private BaseTabItem tabsContact;
    private BaseTabItem tabsWork;
    private BaseTabItem tabsChart;
    private BaseTabItem tabsMine;

    private Intent locationService;
    private int count = 0;
    private AppUpdataBean appUpdataBean;
    private boolean mIsExit = false;
    private NewsFragment newsFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            Intent intent = new Intent(this, WelcomeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            return;
        }
        setContentView(R.layout.activity_main);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);
        if (StringUtils.value(YunLongApplication.BASE_URL).trim().length() < 1) {
            initApi();
        }
        initListener();
    }

    private void initListener() {
        initBottomBar();
        // 融云 初始化
        initIMRong();

        // 友盟推送接口
        initUmengPush();
        // 初始化 更新
        ServiceRequestManager.getManager().appUpdata(this, "2", this);
        // 后台定位服务
        locationService = new Intent(this, LocationService.class);
        startService(locationService);
        bindService(locationService, conn, Context.BIND_AUTO_CREATE);
        check2ShowDialog();
    }

    private void initBottomBar() {
        PageNavigationView tab = findViewById(R.id.tab);
        viewPager = findViewById(R.id.viewPager);
        tabsMessage = newItem(R.mipmap.ic_message_def, R.mipmap.ic_message_sel, "消息");
        tabsContact = newItem(R.mipmap.ic_contact_def, R.mipmap.ic_contact_sel, "通讯录");
        tabsWork = newRoundItem(R.mipmap.ic_center_def, R.mipmap.ic_center_sel, "工作");
        tabsChart = newItem(R.mipmap.ic_chart_def, R.mipmap.ic_chart_sel, "报表");
        tabsMine = newItem(R.mipmap.ic_mine_def, R.mipmap.ic_mine_sel, "我的");

        ArrayList<Fragment> fragmentList = new ArrayList<>();
        newsFragment = new NewsFragment();
        fragmentList.add(newsFragment);
        fragmentList.add(new ContactsFragment());
        fragmentList.add(new NewWorkFragment());
        fragmentList.add(new ChartFragment());
        fragmentList.add(new MeFragment());
        NavigationController navigationController = tab.custom()
                .addItem(tabsMessage)
                .addItem(tabsContact)
                .addItem(tabsWork)
                .addItem(tabsChart)
                .addItem(tabsMine)
                .build();
        viewPager.setAdapter(new ViewpagerFragmentAdapter(getSupportFragmentManager(), fragmentList));
        viewPager.setOffscreenPageLimit(5);
        //自动适配ViewPager页面切换
        navigationController.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(2);
    }

    private void initUmengPush() {
        HashMap<String, String> map = new HashMap<>();
        map.put("deviceToken", YunLongApplication.getDeviceToken());
        map.put("phoneFlag", "0");
        if ("1".equals(companyType)) {
            map.put("userId", ownerBean.getRows().getEmployeeId());
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
        } else {
            map.put("userId", serviceLoginBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
        }
        ServiceRequestManager.getManager().pushInit(this, JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                LogUtil.e("推送登录成功");
            }

            @Override
            public void onException(int requestId, String code) {
                LogUtil.e("推送登录失败");
            }
        });
    }

    private void initIMRong() {
        if (getApplicationInfo().packageName.equals(PackageUtils.getCurProcessName(getApplicationContext()))) {
            RongIM.init(this);
            // 自定义消息
            RongIM.registerMessageType(NoticeMessage.class);
            RongIM.getInstance().registerMessageTemplate(new NoticeMessageItemProvider(this));
            RongIM.setConnectionStatusListener(connectionStatusListener);
        }
        if ("1".equals(companyType)) {
            RongIM.connect(ownerBean.getRows().getToken(), connectCallback);
        } else {
            RongIM.connect(serviceLoginBean.getRows().getToken(), connectCallback);
        }
        // 接受消息监听
        RongIM.getInstance().setOnReceiveMessageListener(onReceiveMessageListener);
        // 发送消息监听
        RongIM.getInstance().setSendMessageListener(onSendMessageListener);
        //
        RongIM.getInstance().setConversationBehaviorListener(onConversationBehaviorListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //未读消息
        updateUnreadLabel();
        refreshCompanyInfo();//刷新公司信息
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        try {
            unbindService(conn);
            stopService(locationService);
        } catch (Exception e) {
        }
    }


    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.e("服务连接成功");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtil.e("服务断开连接");
        }
    };

    /**
     * 融云IM 登录
     */
    private RongIMClient.ConnectCallback connectCallback = new RongIMClient.ConnectCallback() {
        @Override
        public void onTokenIncorrect() {
            LogUtil.e("融云token错误");
        }

        @Override
        public void onSuccess(String s) {
            LogUtil.e("融云登录成功");
            // 设置当前用户头像昵称
            String pic;
            String name;
            if ("1".equals(companyType)) {
                pic = Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar();
                name = ownerBean.getRows().getName();
                RongIM.getInstance().setCurrentUserInfo(new UserInfo(ownerBean.getRows().getEmployeeId(), name, Uri.parse(pic)));
            } else {
                pic = Api.$().SERVICE_FILE_URL + serviceLoginBean.getRows().getAvatar();
                name = serviceLoginBean.getRows().getName();
                RongIM.getInstance().setCurrentUserInfo(new UserInfo(serviceLoginBean.getRows().getEmployeeId(), name, Uri.parse(pic)));
            }
            RongIM.getInstance().setMessageAttachedUserInfo(true);
            // 设置客服信息
            RongUserInfoManager.getInstance().setUserInfo(new UserInfo("1",
                    "云呐客服", Uri.parse(Api.$().MiDDLE_URL + "image/custom_service.png")));
        }

        @Override
        public void onError(RongIMClient.ErrorCode errorCode) {
            LogUtil.e("融云登录失败" + errorCode);
        }
    };

    /**
     * 发送消息
     */
    RongIM.OnSendMessageListener onSendMessageListener = new RongIM.OnSendMessageListener() {
        @Override
        public io.rong.imlib.model.Message onSend(io.rong.imlib.model.Message message) {
            MessageContent content = message.getContent();
            if (Conversation.ConversationType.GROUP == message.getConversationType()) {
                Group group = RongUserInfoManager.getInstance().getGroupInfo(message.getTargetId());
                if (group != null) {
                    if (content instanceof TextMessage) {
                        ((TextMessage) content).setExtra(group.getName());
                    } else if (content instanceof VoiceMessage) {
                        ((VoiceMessage) content).setExtra(group.getName());
                    } else if (content instanceof MediaMessageContent) {
                        ((MediaMessageContent) content).setExtra(group.getName());
                    } else if (content instanceof InformationNotificationMessage) {
                        ((InformationNotificationMessage) content).setExtra(group.getName());
                    }
                }
            } else if (Conversation.ConversationType.PRIVATE == message.getConversationType()) {
                String extra = "phone";
                if ("1".equals(companyType)) {
                    extra += "_1";
                } else {
                    extra += "_2";
                }
                if (content instanceof TextMessage) {
                    ((TextMessage) content).setExtra(extra);
                } else if (content instanceof VoiceMessage) {
                    ((VoiceMessage) content).setExtra(extra);
                } else if (content instanceof MediaMessageContent) {
                    ((MediaMessageContent) content).setExtra(extra);
                } else if (content instanceof InformationNotificationMessage) {
                    ((InformationNotificationMessage) content).setExtra(extra);
                } else if (content instanceof RichContentMessage) {
                    ((RichContentMessage) content).setExtra(extra);
                } else if (content instanceof NoticeMessage) {
                    ((NoticeMessage) content).setExtra(extra);
                }
            }
            return message;
        }

        @Override
        public boolean onSent(io.rong.imlib.model.Message message, RongIM.SentMessageErrorCode sentMessageErrorCode) {
            if (message.getSentStatus() == io.rong.imlib.model.Message.SentStatus.FAILED) {
                if (sentMessageErrorCode == RongIM.SentMessageErrorCode.NOT_IN_CHATROOM) {
                    //不在聊天室
                } else if (sentMessageErrorCode == RongIM.SentMessageErrorCode.NOT_IN_DISCUSSION) {
                    //不在讨论组
                } else if (sentMessageErrorCode == RongIM.SentMessageErrorCode.NOT_IN_GROUP) {
                    //不在群组
                    EventBus.getDefault().post(new ChatNotGroupEvent());
                } else if (sentMessageErrorCode == RongIM.SentMessageErrorCode.REJECTED_BY_BLACKLIST) {
                    //你在他的黑名单中
                }
            }
            return true;
        }
    };

    /**
     * 融云IM 消息监听
     */
    private RongIMClient.OnReceiveMessageListener onReceiveMessageListener = new RongIMClient.OnReceiveMessageListener() {
        @Override
        public boolean onReceived(io.rong.imlib.model.Message message, int i) {
            if (Conversation.ConversationType.GROUP == message.getConversationType()) {
                MessageContent content = message.getContent();
                String extra = "";
                if (content instanceof TextMessage) {
                    extra = ((TextMessage) content).getExtra();
                } else if (content instanceof VoiceMessage) {
                    extra = ((VoiceMessage) content).getExtra();
                } else if (content instanceof MediaMessageContent) {
                    extra = ((MediaMessageContent) content).getExtra();
                } else if (content instanceof InformationNotificationMessage) {
                    extra = ((InformationNotificationMessage) content).getExtra();
                } else if (content instanceof NoticeMessage) {
                    extra = ((NoticeMessage) content).getExtra();
                }
                if (!TextUtils.isEmpty(extra)) {
                    Group group = new Group(message.getTargetId(), extra, Uri.parse("xxx"));
                    RongUserInfoManager.getInstance().setGroupInfo(group);
                }
            }
            refreshUIWithMessage(false);
            return false;
        }
    };

    RongIM.ConversationBehaviorListener onConversationBehaviorListener = new RongIM.ConversationBehaviorListener() {
        @Override
        public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
            return false;
        }

        @Override
        public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
            return false;
        }

        @Override
        public boolean onMessageClick(Context context, View view, io.rong.imlib.model.Message message) {
            MessageContent content = message.getContent();
            if (content instanceof RichContentMessage) {
                // 自己处理 通知跳转的页面
                String url = ((RichContentMessage) content).getUrl();
                if (!TextUtils.isEmpty(url)) {
                    WebBrowserActivity.openActivity(mContext, url);
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean onMessageLinkClick(Context context, String s) {
            return false;
        }

        @Override
        public boolean onMessageLongClick(Context context, View view, io.rong.imlib.model.Message message) {
            return false;
        }
    };


    /**
     * 融云监听
     */
    RongIMClient.ConnectionStatusListener connectionStatusListener = new RongIMClient.ConnectionStatusListener() {
        @Override
        public void onChanged(ConnectionStatus connectionStatus) {
            switch (connectionStatus) {
                case CONNECTED://连接成功。
                    LogUtil.e("融云初始化成功");
                    break;
                case DISCONNECTED://断开连接。

                    break;
                case CONNECTING://连接中。

                    break;
                case NETWORK_UNAVAILABLE://网络不可用。

                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                    final Activity taskTop = AppManager.getAppManager().currentActivity();
                    if (taskTop == null) return;
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showSingleDialog(taskTop, "您的账号已在其他设备上登录，如不是本人操作，请尽快修改密码。", false, new DialogUtils.OnDialogClickListener() {
                                @Override
                                public void onCancel(Dialog dialog) {
                                }

                                @Override
                                public void onConfirm(Dialog dialog) {
                                    dialog.dismiss();
                                    ((BaseActivity) taskTop).exitApp();
                                }
                            });
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };

    // eventBus 回调事件
    // region
    // 消息数量
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(MessageRefreshEvent event) {
        if (!TextUtils.isEmpty(event.count)) { //刷新回话界面
            count = Integer.parseInt(event.count);
            updateUnreadLabel();
        } else {
            refreshUIWithMessage(event.b);
        }
    }

    // 关闭app
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(AppInformationEvent event) {
        switch (event.getAppInfo()) {
            case AppInformationEvent.ExitApp:
                this.finish();
                break;
            default:
                break;
        }
    }

    // 工单总数
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(WorkNumberEvent event) {
        if (event.total != 0) {
            tabsWork.setHasMessage(true);
        } else {
            tabsWork.setHasMessage(false);
        }
    }

    //切换公司刷新
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(MainRefreshEvent event) {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    // endregion

    // 实现接口 回调事件
    //region
    @Override
    public void onBackPressed() {
        if (mIsExit) {
            // 退出app
            // ActivityManager.getInstance().exit();
            moveTaskToBack(true);
        } else {
            mIsExit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIsExit = false;
                }
            }, 2000);
            BeToastUtil.get().showCenterInfoMsg(getApplicationContext(), "再按一次回到桌面");
        }
    }


    private void updateUnreadLabel() {
        int unreadMessageCount = RongIM.getInstance().getTotalUnreadCount();
        if (tabsMessage != null) {
            tabsMessage.setMessageNumber(unreadMessageCount + count);
        }
    }

    /**
     * 更新会话列表
     *
     * @param b
     */
    private void refreshUIWithMessage(final boolean b) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateUnreadLabel();
                if (newsFragment != null) {
                    newsFragment.refresh(b);
                }
            }
        });
    }

    @Override
    public void onException(int requestId, String code) {
    }

    // 版本更新 回调
    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1: // 更新接口 回调
//                showUpdataDialog();
                appUpdataBean = new Gson().fromJson(result, AppUpdataBean.class);
                if (appUpdataBean.getMessage().getCode() == 200) {
                    int versionCode = PackageUtils.getVersionCode(this);
                    if (!TextUtils.isEmpty(StringUtils.value(appUpdataBean.getRows().getVersionName()))
                            && versionCode < Integer.parseInt(appUpdataBean.getRows().getVersionName())) {
                        // 版本不一致  需要更新
                        showUpdataDialog();
                    } else {
                        checkFirstGuide();
                    }
                } else {
                    checkFirstGuide();
                }
                break;
            case 2: //个推 回调
                break;
            case 879:
                FriendEnterpriseBean enterpriseBean = new Gson().fromJson(result, FriendEnterpriseBean.class);
                if (enterpriseBean != null) {
                    AppHelper.setMyCompanyInfo(enterpriseBean);
                }
                break;
            case 888:
                LogUtil.e("result:    " + result);
                LoginGuideBean bean = new Gson().fromJson(result, LoginGuideBean.class);
                //返回值为是否第一次登录（0否1是）
                if ("1".equals(StringUtils.value(bean.getRows()))) {
                    showGuideView();
                }
                break;
            default:
                break;
        }
    }

    private void checkFirstGuide() {
        //检查是否第一次登陆开启引导
        String userName = "";
        if ("2".equals(companyType)) {
            userName = StringUtils.value(serviceLoginBean.getRows().getUserName());
        } else {
            userName = StringUtils.value(ownerBean.getRows().getUserName());
        }
        ServiceRequestManager.getManager().checkLoginGuide(this, userName, this);
    }


    private void check2ShowDialog() {
        HashMap<String, String> hashMap = new HashMap<>();
        if ("2".equals(YunLongApplication.getCompanyType())) {
            hashMap.put("serviceProviderCode", StringUtils.value(serviceLoginBean.getRows().getServiceProviderCode()));
            hashMap.put("currentUserId", StringUtils.value(serviceLoginBean.getRows().getEmployeeId()));
        } else {
            hashMap.put("ownerCode", StringUtils.value(ownerBean.getRows().getOwnerCode()));
            hashMap.put("currentUserId", StringUtils.value(ownerBean.getRows().getEmployeeId()));
        }
        ServiceRequestManager.getManager().dialogInvite(this, JsonMapUtil.mapToJson(hashMap), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                CommonBean bean = new Gson().fromJson(result, CommonBean.class);
                if (bean != null && bean.getRows() != null) {
                    if (StringUtils.value(bean.getRows()).equals("1")) {
                        showCooperationView();
                    }
                }
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
    }


    private void showGuideView() {
        String[] arry = new String[3];
        arry[0] = "欢迎使用";
        arry[1] = "“云呐IT服务交互台”";
        arry[2] = "您想要开始引导吗？";
        DialogUtils.showGuidePop(this, viewPager, R.mipmap.icon_guide_start, arry,
                new DialogUtils.OnGuideListener() {
                    @Override
                    public void onButtonClick(PopupWindow popupWindow, Button button) {
                        switch (StringUtils.value(button.getText())) {
                            case "开始引导":
                                GuideListActivity.openActivity(MainActivity.this);
                                break;
                            case "不用谢谢":
                                popupWindow.dismiss();
                                break;
                            default:
                                break;

                        }
                    }
                }, "开始引导", "不用谢谢");
    }

    /**
     * 邀请好友企业弹窗提醒
     */
    private void showCooperationView() {
        String[] buttons = new String[2];
        buttons[0] = "邀请已上线的合作伙伴";
        buttons[1] = "邀请对方注册";
        final String inviteName;
        final String invitePhone;
        if ("2".equals(YunLongApplication.getCompanyType())) {
            inviteName = StringUtils.value(serviceLoginBean.getRows().getName());
            invitePhone = SharedPreUtil.getString(this, "service_mobile", "");
        } else {
            inviteName = StringUtils.value(ownerBean.getRows().getName());
            invitePhone = SharedPreUtil.getString(this, "owner_mobile", "");
        }
        String[] arry = new String[3];
        arry[0] = "贵公司没有好友企业，你可以选择";
        arry[1] = "以下选项，尽快拥有合作伙伴，一";
        arry[2] = "起协同运维。";
        DialogUtils.showGuidePop2(this, viewPager, R.mipmap.icon_guide_no_friend, arry,
                new DialogUtils.OnGuideListener() {
                    @Override
                    public void onButtonClick(PopupWindow popupWindow, Button button) {
                        switch (StringUtils.value(button.getText())) {
                            case "添加推荐服务商“联泰信息”":
                                addLianTaiFriend();
                                break;
                            case "邀请已上线的合作伙伴":
                                MessageCompanyActivity.OpenActivity(MainActivity.this);
                                break;
                            case "邀请对方注册":
                                String copy = String.format(Api.$().InviteUrl, getCompanyCode(), StringUtils.value(inviteName), StringUtils.value(invitePhone));
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 创建普通字符型ClipData
                                ClipData mClipData = ClipData.newPlainText("Label", copy);
                                cm.setPrimaryClip(mClipData);
                                showCenterSuccessMsg("已经复制到粘贴板，快去分享吧");
                                popupWindow.dismiss();
                                break;
                            default:
                                break;

                        }
                    }
                }, buttons);
    }


    private void addLianTaiFriend() {
        if ("1".equals(YunLongApplication.getCompanyType())) {
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            HashMap<String, String> map = new HashMap();
            map.put("currentUserId", StringUtils.value(ownerBean.getRows().getEmployee().getEmployeeId()));
            manager.addLtsFriends(this, JsonMapUtil.mapToJson(map), new HttpTaskListener() {
                @Override
                public void onSuccess(int requestId, String result) {
                    CommonBean bean = new Gson().fromJson(result, CommonBean.class);
                    if (bean.getMessage() != null) {
                        switch (StringUtils.value(bean.getMessage().getCode())) {
                            case "200":
                                showCenterSuccessMsg("添加成功！");
                                break;
                            case "1007":
                                showCenterInfoMsg("用户不存在");
                                break;
                            case "201":
                                showCenterInfoMsg("系统执行异常");
                                break;
                            case "1004":
                                showCenterInfoMsg("数据不存在");
                                break;
                            case "1005":
                                showCenterInfoMsg("公司已绑定");
                                break;
                            case "1032":
                                showCenterInfoMsg("您的企业未通过认证");
                                break;
                            default:
                                showCenterInfoMsg(StringUtils.value(bean.getMessage().getMessage()));
                                break;
                        }
                    }
                }

                @Override
                public void onException(int requestId, String code) {

                }
            });
        }

    }


    // 更新安装 APK
    //region

    private void showUpdataDialog() {
        DialogUtils.showUpdatePop(this, viewPager, appUpdataBean.getRows().getDescription(),
                appUpdataBean.getRows().getVersionNo(), appUpdataBean.getRows().getIsUpdate(), new DialogUtils.OnUpdateListener() {
                    @Override
                    public void onUpdate(PopupWindow popupWindow) {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(appUpdataBean.getRows().getUpdateUrl());
                        intent.setData(content_url);
                        startActivity(intent);
                    }
                });
    }


    //endregion


    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(0xffb8bfcc);
        mainTab.setTextCheckedColor(0xff689df8);
        return mainTab;
    }

    /**
     * 中间圆形圆形tab
     */
    private BaseTabItem newRoundItem(int drawable, int checkedDrawable, String text) {
        SpecialTabRound mainTab = new SpecialTabRound(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(0xffb8bfcc);
        mainTab.setTextCheckedColor(0xff689df8);
        return mainTab;
    }


}
